<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>书籍</title>
<script src='/js/jquery-3.6.4.min.js'></script>
<link href="/js/jquery-ui-1.13.2/jquery-ui.min.css" rel="stylesheet">
<script src='/js/jquery-ui-1.13.2/jquery-ui.min.js'></script>
</head>
<style>
  #menu {
    position: absolute;
    background-color: #fff;
    border: 1px solid #ccc;
    padding: 10px;
    display: none;
  }
  
  #mydiv{
  	margin:10px;
  	padding:10px;
  	width:100%;
  	border: 1px solid #ccc;
  	
  }
  
  .sq{
  	border: 1px solid #ccc;
  }
  
  #bq {
    position: absolute;
    background-color: #fff;
    border: 1px solid #ccc;
    padding: 10px;
    display: none;
    
  }
  
  #tuimg {
    position: absolute;
    background-color: #fff;
    border: 1px solid #ccc;
    padding: 10px;
    display: none;
    
  }
  
  #createbq {
     background-color: #f2f2f2;
     
     border: 1px solid #dddddd;
   }

   /* div 元素鼠标滑过状态下的样式 */
   #createbq:hover {
     background-color: #d9d9d9;
   }
   
   #createimg {
     background-color: #f2f2f2;
     
     border: 1px solid #dddddd;
   }

   /* div 元素鼠标滑过状态下的样式 */
   #createimg:hover {
     background-color: #d9d9d9;
   }
   
   #searchyao {
     background-color: #f2f2f2;
     
     border: 1px solid #dddddd;
   }

   /* div 元素鼠标滑过状态下的样式 */
   #searchyao:hover {
     background-color: #d9d9d9;
   }
   
   #yao {
        position: absolute;
        top: 100px;
        left: 100px;
        z-index: 9999;
        padding: 10px;
        width:1000px;
        height:500px;
        overflow: auto;
        background-color: #fff;
        border-radius: 5px;
        box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
        display: none;
      }
      
      .container {
        border: 1px solid #ccc;
        border-radius: 5px;
        padding: 5px;
        width: 98%;
        background-color: #f8f8f8;
        color: #333;
        box-shadow: 3px 3px 3px #888888;
        margin-bottom:3px;
    }
    
    /* 设置 title 的样式 */
    .title {
      border-bottom: 1px dotted black;
      background-color: #f8f8a8;
    }
    
    /* 设置 content 的样式 */
    .content {
        
    }
    
    /* 设置 remark 的样式 */
    .remark {
       border-top: 1px dotted black;
    }
    
    .image-wrapper {
  width: 500px;
  height: 300px;
  position: relative;
  overflow: hidden;
}

.image-wrapper img {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  max-width: 100%;
  max-height: 100%;
}
    

</style>
<body>

<div style='white-space: pre-wrap;' id='mydiv'>
#(book)
</div>

<div id="menu">
	<div id='createbq'>
	  添加书签
	</div>
	<hr>
	<div id="searchyao">
	  查询药物
	</div>
	<hr>
	<div id="createimg">
	  添加图片
	</div>
</div>

<div id="bq">
  <div><button style='float:right;' onclick='closeBq()'>X</button></div>
  <input id='zhengids' style='display:none' ></input>
  <input id='zhengnames' style='display:none' ></input>
  <input id='shownames' style='width:80%;margin-bottom:2px' placeholder='请选择症状'></input>
  <textarea id='remark' style='width:97%;min-width:97%;min-height: 50%' ></textarea>
  <div style='float:right;'><button onclick='save()'>保存</button><button onclick='dele()'>删除</button></div>
  <div style='clear:both'></div>
</div>

<div id="yao" ></div>

<div id="tuimg">
  <div><button style='float:right;' onclick='closeimg()'>X</button></div>
	  <input type="file" name="img" id='img'>
	  <div class="image-wrapper">
	  <img alt="" id='showimg'  />
	  </div>
	  <div>
	  <textarea id='imgremark' name='imgremark' style='width:97%;min-width:97%;min-height: 50%' ></textarea></div>
	  <div style='float:right;'><button onclick='saveimg()'>保存</button><button onclick='deleimg()'>删除</button></div>
	  <div style='clear:both'></div>
</div>

<input id='bookname' style='display:none' value="#(name)" ></input>

<script>

  $(document).ready(function(){
	$("#bq").draggable();
	$("#bq").resizable();
	$('#yao').draggable().resizable();
	$('#tuimg').draggable().resizable();
	$('#shownames').click(function() {
		var ids=$('#zhengids').val();
		var names=$('#zhengnames').val();
		var encodedStr = encodeURIComponent(names);
		// 打开子窗口
		window.open('/zheng?ids='+ids+'&names='+encodedStr, 'newwindow', 'height=700, width=1000, top=50, left=50, toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no')
		
	});

	$('#img').on('change', function() {
		  var file = this.files[0];
		  var reader = new FileReader();
		  reader.onload = function(e) {
		    $('#showimg').attr('src', e.target.result);
		  };
		  reader.readAsDataURL(file);
		});
	
  });
  
  var myDiv = document.getElementById('mydiv');
  var menu = document.getElementById('menu');
  var yao = document.getElementById('yao');
  var searchyao = document.getElementById('searchyao');
  var createbq = document.getElementById('createbq');
  var createimg = document.getElementById('createimg');
  var bq = document.getElementById('bq');
  var tuimg = document.getElementById('tuimg');
  var remark =  document.getElementById('remark');
  var imgremark =  document.getElementById('imgremark');
  var showimg = document.getElementById("showimg");
  
  var selectedText = '';
  var isMenuVisible = false;
  var isYaoVisible = false;
  var isBqVisible = false;
  var bqid='';
  var isimgVisible = false;
  var imgid='';

  var closeBq = function() {
	    if (!isBqVisible) {
	      return;
	    }
	    
	    bqid='';
	    isBqVisible = false;
	    bq.style.display = 'none';
	    remark.value ='';
	    $('#zhengids').val('');
	    $('#zhengnames').val('');
	    $('#shownames').val('');
	    
  };
  var closeimg = function() {
	    if (!isimgVisible) {
	      return;
	    }
	    
	    imgid='';
	    isimgVisible = false;
	    tuimg.style.display = 'none';
	    imgremark.value ='';
	    $('#img').val('');
	    showimg.setAttribute("src", '');
	    
};
  myDiv.addEventListener('mousedown', closeimg);
  myDiv.addEventListener('mousedown', closeBq);
  myDiv.addEventListener('mousedown', closeYao);
  var closeYao = function(event) {
	    if (!isYaoVisible) {
	      return;
	    }
	    if (event.target === yao || yao.contains(event.target)) {
	      return;
	    }
	    isYaoVisible = false;
	    yao.style.display = 'none';
	    document.removeEventListener('mousedown', closeYao);
  };
  var closeMenu = function(event) {
    if (!isMenuVisible) {
      return;
    }
    if (event.target === menu || menu.contains(event.target)) {
      return;
    }
    isMenuVisible = false;
    menu.style.display = 'none';
    document.removeEventListener('mousedown', closeMenu);
  };
  myDiv.addEventListener('contextmenu', function(event) {
    event.preventDefault();
    var selection = window.getSelection();
    selectedText = selection.toString().trim();
    if (selectedText !== '') {
    	menu.style.left = event.pageX + 'px';
        menu.style.top = event.pageY + 'px';
        menu.style.display = 'block';
        isMenuVisible = true;
        document.addEventListener('mousedown', closeMenu);
    }
    
  });
  
  bq.addEventListener("mousedown", function(event) {
	if (event.buttons === 1) {
		
	}
  });
  
  menu.addEventListener("mousedown", function(event) {
	 if (event.buttons === 1) {
	   event.preventDefault();
	 }
  });

//点击新增图片菜单
  createimg.addEventListener("click",function(event){
	  
	isMenuVisible = false;
	menu.style.display = 'none';
	var selection = window.getSelection();
	if (selection.toString()) {
		var range = selection.getRangeAt(0);
        var startNode = range.startContainer;
        var startOffset = range.startOffset;
        var endNode = range.endContainer;
        var endOffset = range.endOffset;
        var time=new Date().getTime();
        var bookname=$('#bookname').val();
        
        var textAfter = document.createElement("div");
        textAfter.id=time+"_img";
        textAfter.innerHTML='<==========================<span style="display:none">'+time+'_img</span>============<span class="sq" onmouseover="getimg('+time+',\''+bookname+'\')">图片</span>====>';
        var color=getRandomColor();
        textAfter.style.color=color;

        if(startNode.nodeName=='#text'&&endNode.nodeName=='#text'){
            endNode.parentNode.insertBefore(textAfter, endNode.nextSibling);
        }else{
			alert("只能选择文字");
			return;
        }

        var divContent = document.querySelector('#mydiv').innerHTML;
        divContent = divContent.replace(/^\n+|\n+$/g, '');
        
        getimg(time,bookname,true)
        fetch('/book/createimg', {
            method: 'POST',
            headers: { 'Content-Type': "application/json" },
            body: encodeURIComponent(JSON.stringify({ content: divContent,time:time,bookname:bookname}))
        })
        .then(response => {
            if (!response.ok) {
              throw new Error('Network response was not ok');
            }
            return response.json();
          })
          .then(data => {
            console.log(data);
            // 在这里对响应数据进行处理
          })
          .catch(error => {
            //console.error('There was a problem with the fetch operation:', error);
          });
	}
  });

  //点击新增书签菜单
  createbq.addEventListener("click",function(event){
	  
	isMenuVisible = false;
	menu.style.display = 'none';
	
	var selection = window.getSelection();
	if (selection.toString()) {
		var range = selection.getRangeAt(0);
        var startNode = range.startContainer;
        var startOffset = range.startOffset;
        var endNode = range.endContainer;
        var endOffset = range.endOffset;
        var time=new Date().getTime();
        var bookname=$('#bookname').val();
        
        var textBefore = document.createElement("div");
        var textAfter = document.createElement("div");
        textBefore.id=time+"_0";
        textAfter.id=time+"_1";
        textBefore.innerHTML='<------------------------------------------------------<span style="display:none">'+time+'_0</span>-----------<span class="sq" onmouseover="getsq('+time+',\''+bookname+'\')">书签</span>---->';
        textAfter.innerHTML='<------------------------------------------------------<span style="display:none">'+time+'_1</span>-------------------->';
        var color=getRandomColor();
        textBefore.style.color=color;
        textAfter.style.color=color;

        if(startNode.nodeName=='#text'&&endNode.nodeName=='#text'){
        	startNode.parentNode.insertBefore(textBefore, startNode);
            endNode.parentNode.insertBefore(textAfter, endNode.nextSibling);
        }else{
			alert("只能选择文字");
			return;
        }

        var divContent = document.querySelector('#mydiv').innerHTML;
        divContent = divContent.replace(/^\n+|\n+$/g, '');
        
        var regex = /<----.*?---->|---->.*?<----/gs;
        selectedText= selectedText.replace(regex, '');
        getsq(time,bookname,true)
        fetch('/book/createsq', {
            method: 'POST',
            headers: { 'Content-Type': "application/json" },
            body: encodeURIComponent(JSON.stringify({ content: divContent,range:selectedText,time:time,bookname:$('#bookname').val()}))
        })
        .then(response => {
            if (!response.ok) {
              throw new Error('Network response was not ok');
            }
            return response.json();
          })
          .then(data => {
            console.log(data);
            // 在这里对响应数据进行处理
          })
          .catch(error => {
            //console.error('There was a problem with the fetch operation:', error);
          });

        
        
     }
  })
  
  //点击查询药菜单
  searchyao.addEventListener("click",function(event){
	  isMenuVisible = false;
	  menu.style.display = 'none';
	  var selection = window.getSelection();
	  var yaost=selection.toString();
	  if (yaost) {
		  fetch('/book/getyao', {
	          method: 'POST',
	          headers: { 'Content-Type': 'application/json' },
	          body: encodeURIComponent(JSON.stringify({ 'yao':yaost }))
	      })
	      .then(response => {
	          if (!response.ok) {
	            throw new Error('');
	          }
	          return response.json();
	        })
	        .then(data => {
	        	
		        if(data.res=='ok'){
			       
			        var yaoja=data.data;
			        var ht='';
			        
			        yaoja.forEach(function(num, index, array) {
		        	    var o=array[index];
		        	    var remark=o.remark;
		        	    var content=o.content;
		        	    var bookname=o.bookname;
		        	    
		        	    content=content.replace(new RegExp('@r@@n@', 'g'), '<br>');
		        	    remark=remark.replace(new RegExp('@r@@n@', 'g'), '<br>');
		        	    remark=remark.replace(new RegExp('@n@', 'g'), '<br>');
		        	    
		        	    ht+='<div class="container"><div class="title">'+bookname+'</div><div class="content">'+content+'</div><div class="remark">备注：'+remark+'</div></div>';
		        	    
		           });
			       
			        yao.innerHTML=ht;
			        yao.style.left = event.pageX + 'px';
  		            yao.style.top = event.pageY -50+ 'px';
			        yao.style.display = 'block';
			        isYaoVisible = true;
			        document.addEventListener('mousedown', closeYao);
			    }else if(data.res=='nodata'){
				    alert("没有找到药物");
				}
	          
	        })
	        .catch(error => {
	          //console.error('', error);
	        });
	  }
  });

  //鼠标滑过书签span
  var oldtime=''
  function getsq(time,bookname,flag){
	  if(isBqVisible==true&&oldtime==time){
		  return;
      }
	  bqid=time;
	  bq.style.left = this.event.pageX + 'px';
      bq.style.top = this.event.pageY+ 'px';
      bq.style.display = 'block';
      isBqVisible = true;
      oldtime=time;
      if(flag){
          return;
      }
      
	  fetch('/book/getsq', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: encodeURIComponent(JSON.stringify({ time: time,bookname:bookname}))
      })
      .then(response => {
          if (!response.ok) {
            throw new Error('');
          }
          return response.json();
        })
        .then(data => {
          //console.log(data);
          var remarkst=data.remark;
          remarkst=remarkst.replace(new RegExp('@n@', 'g'), '\n');
          remarkst=remarkst.replace(new RegExp('@r@', 'g'), '');
          remark.value=remarkst;
          var ids=data.bqid;
          var names=data.bq;
          $('#zhengids').val(ids);
          $('#zhengnames').val(names);
          $('#shownames').val(names.replace(new RegExp('@', 'g'), ' '));
          // 在这里对响应数据进行处理
        })
        .catch(error => {
          //console.error('', error);
        });
  }

  //鼠标滑过img
  var oldimgtime=''
  function getimg(time,bookname,flag){
	  if(isimgVisible==true&&oldimgtime==time){
		  return;
      }
	  imgid=time;
	  
	  tuimg.style.left = this.event.pageX + 'px';
	  if(flag){
		  tuimg.style.top = this.event.pageY-100+ 'px';
	  }else{
		  tuimg.style.top = this.event.pageY+ 'px';
	  }
	  
	  tuimg.style.display = 'block';
      isimgVisible = true;
      oldimgtime=time;
      if(flag){
          return;
      }
      
	  fetch('/book/getimg', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: encodeURIComponent(JSON.stringify({ time: time,bookname:bookname}))
      })
      .then(response => {
          if (!response.ok) {
            throw new Error('');
          }
          return response.json();
        })
        .then(data => {
          //console.log(data);
          var remarkst=data.remark;
          remarkst=remarkst.replace(new RegExp('@n@', 'g'), '\n');
          remarkst=remarkst.replace(new RegExp('@r@', 'g'), '');
          imgremark.value=remarkst;
          // 在这里对响应数据进行处理
          var type=data.type;
          var newsrc="/book/"+bookname+"/"+time+type;
          console.log(newsrc)
          showimg.setAttribute("src", newsrc);
        })
        .catch(error => {
          //console.error('', error);
        });
  }
  
  //编辑图片
  function saveimg(){
	  if(imgid!=''){
		  var fileInput = document.getElementById('img');
		  var remarkst = imgremark.value;
		  var bookname = $('#bookname').val();
		  var time = imgid;
		  var file = fileInput.files[0];
		  if(file!=undefined){
			  var fileType = file.type;
				 
			  if (fileType == 'image/png' || fileType == 'image/jpeg' || fileType == 'image/gif'|| fileType == 'image/jpg' ) {
			  } else {
			    alert('请选择图像文件！');
			    return false;
			  }
		  }
		  
		
		  var formData = new FormData();

		  formData.append('file', file);
		  formData.append('bookname', bookname);
		  formData.append('time', time);
		  formData.append('remark', remarkst);

		  var xhr = new XMLHttpRequest();
		  xhr.open('POST', '/book/editimg', true);

		  xhr.onload = function() {
		    if (xhr.status === 200) {
		    	closeimg();
		      alert('保存成功！');
		    } else {
		      alert('保存失败！');
		    }
		  };

		  xhr.send(formData); 
	  }
  }

  //编辑标签
  function save(){ 
	  if(bqid!=''){
		  var remarkst =remark.value;
		  var ids=$('#zhengids').val();
          var names=$('#zhengnames').val();
          
		  fetch('/book/editsq', {
	          method: 'POST',
	          headers: { 'Content-Type': 'application/json' },
	          body: encodeURIComponent(JSON.stringify({ time: bqid,remark:remarkst,id:ids,name:names,bookname:$('#bookname').val()}))
	      })
	      .then(response => { 
	          if (!response.ok) {
	            throw new Error('');
	          }
	          return response.json();
	        })
	        .then(data => {
		      if(data.res=='ok'){
		    	  closeBq();
			  }
	          
	        })
	        .catch(error => {
	          //console.error('', error);
	        });
	  }
  }

//删除图片
  function deleimg(){
 	 if(imgid!=''){

 		if(!confirm("确认要删除？")){ 
 	 		return;
 		}
 	 	 
 		 var div0 = document.getElementById(imgid+'_img');
 	   	 if (div0) {
 	   	    div0.parentNode.removeChild(div0);
 	   	 }
 	   	 
 		 var divContent = document.querySelector('#mydiv').innerHTML;
 		 divContent = divContent.replace(/^\n+|\n+$/g, '');
 		 var pathsrc=$('#showimg').attr('src');
 		 var imgname=pathsrc.substring(pathsrc.lastIndexOf('/')+1,pathsrc.length);
 		
 		 fetch('/book/deleimg', {
 	          method: 'POST',
 	          headers: { 'Content-Type': 'application/json' },
 	          body: encodeURIComponent(JSON.stringify({ imgid: imgid,content:divContent,bookname:$('#bookname').val(),imgname:imgname}))
 	      })
 	      .then(response => {
 	          if (!response.ok) {
 	            throw new Error('');
 	          }
 	          return response.json();
 	        })
 	        .then(data => {
 		      if(data.res=='ok'){
 		    	 closeimg();
 			  }
 	          
 	        })
 	        .catch(error => {
 	          //console.error('', error);
 	        });
 	 }
  }

 //删除标签
 function dele(){
	 if(bqid!=''){

		 if(!confirm("确认要删除？")){ 
	 	 		return;
	 	 }
		 
		 var div0 = document.getElementById(bqid+'_0');
	   	 if (div0) {
	   	    div0.parentNode.removeChild(div0);
	   	 }
	   	 var div1 = document.getElementById(bqid+'_1');
	   	 if (div1) {
	   	    div1.parentNode.removeChild(div1);
	   	 }
		 var divContent = document.querySelector('#mydiv').innerHTML;
		 divContent = divContent.replace(/^\n+|\n+$/g, '');
		 fetch('/book/delesq', {
	          method: 'POST',
	          headers: { 'Content-Type': 'application/json' },
	          body: encodeURIComponent(JSON.stringify({ bqid: bqid,content:divContent,bookname:$('#bookname').val()}))
	      })
	      .then(response => {
	          if (!response.ok) {
	            throw new Error('');
	          }
	          return response.json();
	        })
	        .then(data => {
		      if(data.res=='ok'){
		    	  closeBq();
			  }
	          
	        })
	        .catch(error => {
	          //console.error('', error);
	        });
	 }
 }
  
 function getRandomColor() {
  var letters = '0123456789ABCDEF';
  var color = '#';
  for (var i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
 }

 function setzhengdata(data){
	 $('#zhengids').val(data.ids);
	 $('#zhengnames').val(data.names);

	 $('#shownames').val(data.names.replace(new RegExp('@', 'g'), ' '));
 }
 

 
</script>
</body>
</html>